package com.wengzw.gateway.utils;

import com.wengzw.commonutils.JwtUtils;
import com.wengzw.gateway.config.TokenDao;
import com.wengzw.gateway.entity.AuthUserDetails;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.DatatypeConverter;

import static com.wengzw.gateway.common.Constant.TOKEN_USER_INFO;
import static com.wengzw.gateway.common.Constant.TOKEN_USER_INFO_USERNAME;


/**
 * jwt 工具类
 */
@Component
public final class JWTUtil {

    private final TokenDao tokenDao;

    public JWTUtil(TokenDao tokenDao) {
        this.tokenDao = tokenDao;
    }

    private static Key getKeInstance(String salt) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        String apiKey = DatatypeConverter.printBase64Binary(salt.getBytes());
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey);
        SecretKeySpec secretKeySpec = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        return secretKeySpec;
    }

    /**
     * 获取jwt的body部分
     *
     * @param token
     * @param salt
     * @return
     */
    public static Map<String, Object> verifyJavaWebToken(String token, String salt) {
        Map<String, Object> jwtClaims = Jwts.parser().setSigningKey(getKeInstance(salt)).parseClaimsJws(token).getBody();
        return jwtClaims;
    }

    public Authentication getAuthentication(String token) {
        try {
            String username = JwtUtils.parse(token);
            if (username != null) {
                AuthUserDetails user = new AuthUserDetails();
                if(tokenDao.isTokenValid(username,token)) {
                    return new UsernamePasswordAuthenticationToken(username, "", user.getAuthorities());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
